<template>
  <div class="cg-filter-row">
    <div class="cg-filter-col" v-for="field in props.fields" :key="field.id">
      <component
        :is="getComponentMapping(field.components || 'cg-input')"
        :value="getComponentValue(field.id)"
      />
    </div>
    <div class="cg-buttons-col">
      <cg-button :color="'#32aafe'" :size="'sm'" :style="{ fontSize: '1em' }" @click="emit('init')">
        查询
      </cg-button>
      <cg-button
        :color="'#32aafe'"
        :size="'sm'"
        :style="{ fontSize: '1em' }"
        @click="emit('reset')"
      >
        重置
      </cg-button>
      <cg-button
        v-for="item in props.extra"
        :key="item.label"
        :color="'#32aafe'"
        :size="'sm'"
        :style="{ fontSize: '1em' }"
        @click="item.onClick"
        v-bind="item"
      >
        {{ item.label }}
      </cg-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { objectFrom } from '../../tools/index'

// 导入组件
import cgInput from '../cg-input/main.vue'
import cgSelect from '../cg-select/main.vue'
import cgButton from '../cg-button/main.vue'

// 定义组件名称
defineOptions({
  name: 'cg-filter-row'
})

interface Props {
  fields?: Array<{
    id: string
    components?: string
    [key: string]: any
  }>
  extra?: Array<{
    label: string
    onClick: () => void
    [key: string]: any
  }>
  data?: Record<string, any>
}

// 定义props
const props = withDefaults(defineProps<Props>(), {
  fields: () => [],
  extra: () => [],
  data: () => ({})
})

// 定义emits
const emit = defineEmits(['init', 'reset'])

// 组件映射
type ComponentType = typeof cgInput | typeof cgSelect | typeof cgButton

const componentMapping: Record<string, ComponentType> = {
  'cg-input': cgInput,
  'cg-select': cgSelect,
  'cg-button': cgButton
}

const getComponentMapping = (componentName: string): ComponentType => {
  return componentMapping[componentName] || cgInput
}

const getComponentValue = (id: string) => {
  return props.data?.[id]
}
</script>

<style lang="scss">
.cg-filter-row {
  padding-top: 1rem;
  padding-bottom: 1rem;

  .cg-filter-col {
    display: inline-block;
    width: 25%;
    padding: 0 5px;
    margin-bottom: 0.5rem;

    .cg-input {
      width: 100%;
    }
  }

  .cg-buttons-col {
    display: inline-block;
    padding: 0 5px;
    margin-bottom: 0.5rem;

    .cg-button + .cg-button {
      margin-left: 0.25rem;
    }
  }
}
</style>
